<template>
  <div class="app-container">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator=">">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>社区资产</el-breadcrumb-item>
      <el-breadcrumb-item>房屋信息</el-breadcrumb-item>
    </el-breadcrumb>
    <br>
    <!--    模糊查询-->
    <!-- v-show="showSearch"：控制元素的显示/隐藏状态 -->
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">

      <el-form-item label="楼栋/单元" prop="selected" label-width="85px">
        <el-cascader :options="options1" @change="handleChange" clearable/>
      </el-form-item>

      <el-form-item label="房屋状态" prop="roomStatus">
        <el-select v-model="queryParams.roomStatus" placeholder="请选择房屋状态" @change="statusChange()" clearable
                   @clear="statusChange()" size="small">
          <el-option v-for="dict in roomStatusOptions" :key="dict.dictValue" :label="dict.dictLabel"
                     :value="dict.dictValue"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
      <el-form-item style="margin-right: 100px">
        <el-select v-model="queryParams.communityId" @change="selectedCommunity(queryParams.communityId)"
                   style="border: 0;position: relative;" filterable placeholder="请选择小区"
                   class="avatar-container right-menu-item hover-effect">
          <el-option v-for="item in options" :key="item.communityId" :label="item.communityName"
                     :value="item.communityId">
          </el-option>
        </el-select>
      </el-form-item>
    </el-form>
    <!--    CRUD+导入按钮-->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd"
            v-hasPermi="['system:room:add']"
        >新增
        </el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
            type="danger"
            icon="el-icon-delete"
            size="mini"
            :disabled="multiple"
            @click="handleDelete"
            v-hasPermi="['system:room:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
            type="warning"
            icon="el-icon-download"
            size="mini"
            @click="handleExport"
            v-hasPermi="['system:room:export']"
        >导出
        </el-button>
      </el-col>
      <!-- <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar> -->
    </el-row>
    <br>
    <!--    数据展示模块-->
    <el-table :data="roomList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="序号" type="index" width="50" align="center">
      </el-table-column>
      <el-table-column label="房间id" v-if="show" align="center" prop="roomId"/>
      <el-table-column label="小区名称" align="center" prop="communityName"/>
      <el-table-column label="楼栋名称" align="center" prop="buildingName"/>
      <el-table-column label="单元名称" align="center" prop="unitName"/>
      <el-table-column label="楼层" align="center" prop="roomLevel"/>
      <el-table-column label="房间名称" align="center" prop="roomName"/>
      <el-table-column label="房间编号" align="center" prop="roomCode"/>
      <el-table-column label="房屋建筑面积" align="center" prop="roomAcreage"/>
      <el-table-column label="算费系数" align="center" prop="roomCost"/>
      <el-table-column label="房屋状态" align="center" prop="roomStatus"/>
      <el-table-column label="是否商铺" align="center" prop="roomIsShop">
        <template slot-scope="scope">
          {{ scope.row.roomIsShop === "Y" ? '是' : '否' }}
        </template>
      </el-table-column>
      <el-table-column label="是否商品房" align="center" prop="roomSCommercialHouse">
        <template slot-scope="scope">
          {{ scope.row.roomSCommercialHouse === "Y" ? '是' : '否' }}
        </template>
      </el-table-column>
      <el-table-column label="房屋户型" align="center" prop="roomHouseType"/>
      <el-table-column label="创建时间" align="center" prop="createTime"/>
      <el-table-column label="备注" align="center" prop="remark"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                     v-hasPermi="['system:room:edit']">修改
          </el-button>
          <!-- v-hasPermi 是一个 自定义指令，通常用于 Vue 前端项目的 权限控制，它检查当前用户是否拥有指定的权限。 -->
          <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                     v-hasPermi="['system:room:remove']">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->
    <div class="block" style="margin-top:15px;">
      <el-pagination
          @current-change="handleCurrentChange"
          :current-page="queryParams.pageNum"
          :page-size="queryParams.pageSize"
          layout="total, prev, pager, next, jumper"
          :total="total">
      </el-pagination>
    </div>

    <!--    添加、修改房屋对话框-->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">

        <el-form-item label="楼栋/单元" prop="unitId" label-width="85px">
          <el-cascader
              v-model="value1"
              :options="options1"
          />
        </el-form-item>


        <el-form-item label="楼层" prop="roomLevel">
          <el-input type="number" v-model="form.roomLevel" placeholder="请输入楼层"/>
        </el-form-item>

        <el-form-item label="房间名称" prop="roomName">
          <el-input v-model="form.roomName" placeholder="请输入房间名称"/>
        </el-form-item>
        <el-form-item label="建筑面积" prop="roomAcreage">
          <el-input v-model="form.roomAcreage" placeholder="请输入房屋建筑面积"/>
        </el-form-item>
        <el-form-item label="算费系数" prop="roomCost">
          <el-input v-model="form.roomCost" placeholder="请输入算费系数"/>
        </el-form-item>
        <el-form-item label="房屋状态" prop="roomStatus">
          <el-select v-model="form.roomStatus" placeholder="请选择房屋状态" data-field="roomStatus">
            <el-option
                v-for="dict in roomStatusOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否商铺">
          <el-radio-group v-model="form.roomIsShop">
            <el-radio
                v-for="dict in roomIsShops"
                :key="dict.dictValue"
                :label="dict.dictValue"
            >{{ dict.dictLabel }}
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="是否商品房" label-width="82px">
          <el-radio-group v-model="form.roomSCommercialHouse">
            <el-radio
                v-for="dict in roomIsShops"
                :key="dict.dictValue"
                :label="dict.dictValue"
            >{{ dict.dictLabel }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="房屋户型" prop="roomHouseType">
          <el-select v-model="form.roomHouseType" placeholder="请选择房屋户型">
            <el-option
                v-for="dict in roomHouseTypeOptions"
                :key="dict.dictValue"
                :label="dict.dictLabel"
                :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容"/>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  // 全局刷新
  inject: ['reload'],
  data() {
    return {
      roomIsShops: [
        {
          dictLabel: "是",
          dictValue: "Y"
        },
        {
          dictLabel: "否",
          dictValue: "N"
        }
      ],
      //选中的小区id
      communityId: "",
      show: false,//控制房间id是否显示
      options: [],//楼栋
      // 查询参数
      queryParams: {
        pageNum: 1,//总页码
        pageSize: 5,//每页显示条数
        roomStatus: null,//房屋状态
        buildingId: null,//楼栋id
        unitId: null,//单元id
        communityId: null,//小区id
      },
      // 显示/隐藏搜索栏
      showSearch: true,
      // 总条数
      total: 20,
      // 获取房屋信息
      roomList: [],
      // 房屋状态字典
      roomStatusOptions: [],
      //楼栋单元级联选择
      options1: [],
      // 选中数组
      ids: [],
      // 是否显示弹出层
      open: false,
      rules: {
        unitId: [
          {required: true, message: '楼栋/单元不能为空', trigger: 'blur'}
        ],
        buildingId: [
          {required: true, message: '楼栋/单元不能为空', trigger: 'blur'}
        ],
        roomName: [
          {required: true, message: '房间名称不能为空', trigger: 'blur'}
        ],
        roomLevel: [
          {required: true, message: "楼层不能为空", trigger: "blur"},
          {pattern: /^[1-9]\d*$/, message: '请输入正确的整数格式', trigger: "change"}
        ],
        roomHouseType: [
          {required: true, message: "房屋户型不能为空", trigger: "blur"}
        ],
        roomIsShop: [
          {required: true, message: "是否商品不能为空", trigger: "blur"}
        ],
        roomSCommercialHouse: [
          {required: true, message: "是否商品房不能为空", trigger: "blur"}
        ],
        roomStatus: [
          {required: true, message: "房屋不能为空", trigger: "blur"}
        ],
        roomAcreage: [
          {required: true, message: '面积不能为空', trigger: 'blur'},
          {
            pattern: /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/,
            message: '请输入正确格式,可保留两位小数',
            trigger: "change"
          }
        ],
      },
      //修改/添加选中的楼栋+单元信息
      value1: [],
      form: {},
      // 房屋户型字典
      roomHouseTypeOptions: [],
      title: "",
      multiple: true,
    }
  },
  created() {
    this.getCommunities()
    this.getRoomStatus()
    this.getRoomType()
  },
  methods: {
    /**变换查询小区时触发*/
    selectedCommunity(value) {
      this.queryParams.communityId = value
      this.queryParams.pageNum = 1
      this.getList();
      this.communityId = value
    },
    /**查询所有小区*/
    getCommunities() {
      this.$http.get('build/getAllCommunity')
          .then((res) => {
            this.options = res.data
            this.queryParams.communityId = this.options[0].communityId
            this.communityId = this.options[0].communityId
            this.getList();
          })
          .catch((res) => {
            this.$message.error(res.msg)
          })

    },
    /** 查询 小区 下 楼栋 单元 房间 列表 */
    getList() {
      this.loading = true;
      this.$http.get("room/getZyRoomList",
          {params: this.queryParams})
          .then((res) => {
            console.log("zy-room->getList=", res.data)
            this.total = res.data.total
            this.roomList = res.data.records
          })
          .catch((res) => {
            this.roomList = []
            this.$message.error(res.msg)
          })
      //楼栋单元选择器初始化-搜索栏
      this.$http.get("room/getZyBuildingAndUnit",
          {params: {"communityId": this.queryParams.communityId}})
          .then((res) => {
            this.options1 = res.data
          })
          .catch((res) => {
            this.$message.error(res.msg)
          })
    },
    /**多选框选中数据*/
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.roomId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /**当前页改变时触发 跳转其他页*/
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getList();
    },
    //获取所有有关的房屋状态
    getRoomStatus() {
      this.$http.get("dict/getLabelList")
          .then((res) => {
            console.log("zy-room->getRoomStatus=", res.data)
            this.roomStatusOptions = res.data
          })
          .catch((res) => {
            this.$message.error(res.msg)
          })
    },
    /**变换查询状态时时触发*/
    statusChange() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.reload();
    },
    /**楼栋单元选中变换时执行的方法*/
    handleChange(value) {
      this.queryParams.buildingId = value[0]
      this.queryParams.unitId = value[1]
      this.queryParams.pageNum = 1
      this.getList();
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 导出按
    handleExport() {
      const requertUrl = `room/getExcel?communityId=${this.communityId}`
      this.$http.post(requertUrl, this.ids, {responseType: 'blob'})
          .then(response => {
            // 确认数据有效
            if (response.data.size === 0) {
              this.$message.error("文件为空");
              return;
            }
            // 创建下载链接
            const url = URL.createObjectURL(new Blob([response.data], {type: 'application/vnd.ms-excel'}));
            const link = document.createElement('a');
            link.href = url;
            //遍历找出社区名称
            let name = ""
            for (const item of this.options) {
              if (this.queryParams.communityId === item.communityId) {
                name = item.communityName
              }
            }
            link.download = name + '房屋信息.xls';
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
            URL.revokeObjectURL(url);
            this.$message.success("导出成功");
          })
          .catch(error => {
            this.$message.error("导出失败");
          });
    },
    // 新增按钮
    handleAdd() {
      if (this.options1.length === 0 || this.options1[0].children.length === 0) {
        this.$message.error("该小区暂无楼栋以及单元，无法注册房屋信息！");
      } else {
        console.log(this.options1);
        this.value1 = [this.options1[0].value, this.options1[0].children[0].value];
        this.form = {
          buildingId: this.value1[0],
          unitId: this.value1[1],
          remark: "",
          roomAcreage: "",
          roomCost: "",
          roomLevel: "",
          roomName: "",
          communityId: this.queryParams.communityId,
          roomStatus: "none",
          roomIsShop: "Y",
          roomSCommercialHouse: "N",
          roomHouseType: "other",
        }

        this.open = true;
        this.title = "添加房屋";
      }

    },
    // 新增的时候回显房屋类型数据
    getRoomType() {
      this.$http.get("dict/getLabelListType")
          .then((res) => {
            this.roomHouseTypeOptions = res.data
          })
          .catch((res) => {
            this.$message.error(res.msg)
          })
    },
    /** 取消 按钮*/
    cancel() {
      this.form = {
        remark: "",
        roomAcreage: "",
        roomCost: "",
        roomLevel: "",
        roomName: "",
        communityId: "",
        roomStatus: "",
        roomIsShop: "",
        roomSCommercialHouse: "",
        roomHouseType: "",
      };
      this.value1 = [this.options1[0].value, this.options1[0].children[0].value];
      this.open = false;
      // this.getList();
    },
    // 新增确认按钮
    submitForm() {
      console.log("zy->room->submitFrom=value1", this.value1)
      this.form.buildingId = this.value1[0];
      this.form.unitId = this.value1[1];
      this.$refs["form"].validate(async valid => {
        if (valid) {
          let msg = (this.form.roomId !== undefined && this.form.roomId !== "") ? "修改" : "添加";
          this.$http.post("/room/updateAndSaveZyRoom", this.form)
              .then((res) => {
                if (res.msg === "1") {
                  this.$message.error(msg + "失败,该小区楼栋单元下此房间已存在！")
                } else {
                  this.$message.success(msg + "成功！")
                  this.getList();
                  this.open = false;
                }
              })
              .catch((res) => {
                this.$message.error(res.msg)
              })
        } else {
          this.$message.warning("请填写规范！")
        }
      })
    },
    handleUpdate(row) {
      // console.log("row",this.roomHouseTypeOptions)
      console.log(row)
      this.form = JSON.parse(JSON.stringify(row)); // 深拷贝
      // 2. 手动设置显示文本（不破坏表单值） 
      for (const item of this.roomStatusOptions) {
        console.log(item.dictValue, item.dictLabel);
        if (this.form.roomStatus === item.dictLabel) {
          this.form.roomStatus = item.dictValue
        }
      }
      for (const item of this.roomHouseTypeOptions) {
        console.log(item.dictValue, item.dictLabel);
        if (this.form.roomHouseType === item.dictLabel) {
          this.form.roomHouseType = item.dictValue
        }
      }
      console.log("row", this.form.roomStatus)
      this.value1 = [row.buildingId, row.unitId]
      this.open = true;
      this.title = "修改房屋 ";
    },
    //单删+批量删除
    handleDelete(row) {
      if (row.roomId !== undefined) {
        this.ids = [row.roomId]
      }
      const dictIds = row.roomId || this.ids;
      console.log("room-handleDelete -dictIds ->", dictIds)
      if (dictIds.length === 0) {
        this.$message.error("请选择要删除的数据！");
      } else {
        this.$confirm('是否确认删除字典编号为"' + dictIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {

          this.$http.post("/room/delZyRoom", this.ids)
              .then((res) => {
                this.$message.success(res.msg);
                this.getList();
              })
              .catch((res) => {
                this.$message.error(res.msg);
              });

        }).catch(() => {
          this.getList()
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        })
      }
    }
  }
}
</script>

<style scoped></style>